#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

#include "addroundkey.h"
#include "fault_insert.h"
#include "fault_oneround.h"
#include "common.h"

void fault_present(unsigned char* plaintext, unsigned char out_fencrypt[], unsigned char* master_key )
{
	unsigned char *encryption_key = master_key;
	unsigned char *in_encryption = plaintext;

	int num=0;

	unsigned char fkey[32][80]  ;
	unsigned char out_foneround[32][64] ;
	unsigned char out_fresult[32][16] ;
	unsigned char ciphertext_fhex[16] ;
	unsigned char flastkey[64] ;

	for ( int i = 0 ; i <=63 ; i++ )
	{
		out_foneround[0][i] = in_encryption[i] ;
	}

	for ( int i = 0 ; i <= 79 ; i++ )
	{
		fkey[0][i] = encryption_key[i] ;
	}

	unsigned max_val = 1 << error_bit_num;
	int fault ;
//	scanf( "%d" , &fault ) ;
	fault = (rand() % (max_val - 1)) + 1;
//	fault = max_val - 1;

	unsigned char fault_arrary[block_bits] ;
	for ( int i = 0 ; i < error_bit_num ;++i )
	{
		fault_arrary[i] = (fault >> i)&0x01 ; 
	}
	
	for ( int i = 1 ; i <= 31 ; i++ )
	{	
		fault_oneround(out_foneround[i-1] , fkey[i-1] , fault_arrary , i , out_foneround[i] , fkey[i] ) ;
	}
	for ( int i = 0 ; i <= 63 ; i++ )
	{
		flastkey[i] = fkey[31][i+16] ;
	}
	AddRoundKey( out_foneround[31] , flastkey , out_fencrypt ) ;

	for ( int i = 0 ; i <= 31 ; i++ )
	{	
		for ( int j = 0 ; j <= 15 ; j++ )
		{	
			out_fresult[i][j] = out_foneround[i][4*j] | (out_foneround[i][4*j+1]<<1) | (out_foneround[i][4*j+2]<<2) | (out_foneround[i][4*j+3]<<3) ;
		}
	}
	for ( int i = 0 ; i <= 15 ; i++ )
	{	
		ciphertext_fhex[i] = out_fencrypt[4*i] | (out_fencrypt[4*i+1]<<1) | (out_fencrypt[4*i+2]<<2) | (out_fencrypt[4*i+3]<<3) ;
	}

		// 	for ( int i = 0 ; i <= 31 ; i++ )
		// 	{	
		// 		for ( int j = 0 ; j <= 15 ; j++ )
		// 		{
		// 			printf( "%x " , out_result[i][j] ) ;
		// 		}
		// 	printf( "\n" ) ;
		// 	}
//  	for ( int i = 15 ; i >= 0 ; i-- )
//  	{
//  		printf( "%x" , ciphertext_fhex[i] ) ;
//  	}
}                            